package ca.etsmtl.gti785.util;

import java.util.ArrayList;
import java.util.Observable;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import ca.etsmtl.gti785.classes.Server;

/**
 * This class is used in the android application as a singleton, giving access to get notifications from the servers.
 * @author Étienne Faucher
 */
public class NotificationsPolling {
	
	private static ArrayList<NotificationsThread> _runningThreads;
	private static NotificationsPolling _instance;
	
	public static NotificationsPolling getInstanceOf()
	{
		if(_instance == null)
		{
			_instance = new NotificationsPolling();
		}
		
		return _instance;
	}
	
	private NotificationsPolling()
	{
		_runningThreads = new ArrayList<NotificationsThread>();
	}
	
	public void AddServer(Server server)
	{
		NotificationsThread notifThread = new NotificationsThread(server);
		
		_runningThreads.add(notifThread);
	}
	
	public void RemoveServer(Server server)
	{
		NotificationsThread toRemove = null;
		for(NotificationsThread item: _runningThreads)
		{
			if(item.getServer() == server)
			{
				item.Stop();
				toRemove = item;
				break;
			}
		}
		
		if(toRemove != null)
		{
			_runningThreads.remove(toRemove);
		}
	}
	
	private class NotificationsThread extends Observable implements Runnable
	{
		private Server _server;
		private Thread _thread;
		private boolean _continue;
		
		public NotificationsThread(Server server)
		{
			_server = server;
			_continue = true;
			_thread = new Thread(this);
			_thread.start();
		}
		
		public void Stop()
		{
			_continue = false;
		}
		
		public Server getServer()
		{
			return _server;
		}
		
		@Override
		public void run() 
		{
			while(_continue)
			{
				try
				{
					HttpClient httpclient = new DefaultHttpClient();
				    HttpResponse httpresponse = httpclient.execute(new HttpGet(_server.getURL() + Constants.Server_GetNotifications));
				    StatusLine statusLine = httpresponse.getStatusLine();
				    if(statusLine.getStatusCode() == HttpStatus.SC_OK)
				    {
				    	_server.SetOnline(true);
				        _server.AddNotifications();
				    	
				    }
				    else if(statusLine.getStatusCode() == HttpStatus.SC_REQUEST_TIMEOUT)
				    {
				    	_server.SetOnline(true);
				    }
				    else
				    {
				    	_server.SetOnline(false);
				    	httpresponse.getEntity().getContent().close();
				        System.out.println(statusLine.getReasonPhrase());
				    }	
				}
				catch(Exception ex)
				{
			    	_server.SetOnline(false);
					System.out.println(ex.getMessage());
				}
			}
		}
	}
}
